/**
 * API测试脚本
 * 用于测试SSO接口的基本功能
 * 
 * 使用方法：
 * 1. 启动服务器: npm run dev
 * 2. 运行测试: node test-api.js
 */

const http = require('http');
const querystring = require('querystring');

// 测试配置
const BASE_URL = 'http://localhost:7001';
const TEST_USER = {
  username: 'testuser_' + Date.now(),
  email: 'test_' + Date.now() + '@example.com',
  password: 'password123'
};

let sessionCookie = '';

/**
 * 发送HTTP请求的工具函数
 */
function makeRequest(method, path, data = null, headers = {}) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: 7001,
      path: path,
      method: method,
      headers: {
        'Content-Type': 'application/json',
        ...headers
      }
    };

    if (sessionCookie) {
      options.headers.Cookie = sessionCookie;
    }

    const req = http.request(options, (res) => {
      let body = '';
      
      res.on('data', (chunk) => {
        body += chunk;
      });

      res.on('end', () => {
        try {
          const responseData = JSON.parse(body);
          
          // 保存Session Cookie
          if (res.headers['set-cookie']) {
            const cookies = res.headers['set-cookie'];
            const sessionCookieHeader = cookies.find(cookie => cookie.includes('SSO_SESSION_ID'));
            if (sessionCookieHeader) {
              sessionCookie = sessionCookieHeader.split(';')[0];
            }
          }
          
          resolve({
            statusCode: res.statusCode,
            headers: res.headers,
            body: responseData
          });
        } catch (error) {
          reject(new Error('Failed to parse JSON response: ' + body));
        }
      });
    });

    req.on('error', (error) => {
      reject(error);
    });

    if (data) {
      req.write(JSON.stringify(data));
    }

    req.end();
  });
}

/**
 * 测试健康检查接口
 */
async function testHealthCheck() {
  console.log('🏥 测试健康检查接口...');
  try {
    const response = await makeRequest('GET', '/health');
    console.log(`✅ 健康检查: ${response.statusCode} - ${JSON.stringify(response.body)}`);
    return true;
  } catch (error) {
    console.log(`❌ 健康检查失败: ${error.message}`);
    return false;
  }
}

/**
 * 测试用户注册接口
 */
async function testUserRegistration() {
  console.log('\\n📝 测试用户注册接口...');
  
  try {
    // 测试成功注册
    console.log(`注册用户: ${TEST_USER.username}`);
    const response = await makeRequest('POST', '/api/sso/register', TEST_USER);
    
    if (response.statusCode === 201 && response.body.success) {
      console.log('✅ 用户注册成功');
      console.log(`   用户ID: ${response.body.data.userId}`);
      return true;
    } else {
      console.log(`❌ 用户注册失败: ${response.statusCode} - ${response.body.message}`);
      return false;
    }
  } catch (error) {
    console.log(`❌ 用户注册异常: ${error.message}`);
    return false;
  }
}

/**
 * 测试参数验证
 */
async function testValidation() {
  console.log('\\n🔍 测试参数验证...');
  
  // 测试缺少参数
  try {
    const response = await makeRequest('POST', '/api/sso/register', {
      username: 'testuser'
      // 缺少email和password
    });
    
    if (response.statusCode === 400) {
      console.log('✅ 参数验证正常 - 缺少必填参数');
    } else {
      console.log('❌ 参数验证失败 - 应该返回400');
    }
  } catch (error) {
    console.log(`❌ 参数验证异常: ${error.message}`);
  }
  
  // 测试重复注册
  try {
    const response = await makeRequest('POST', '/api/sso/register', TEST_USER);
    
    if (response.statusCode === 409) {
      console.log('✅ 重复注册验证正常 - 用户名已存在');
    } else {
      console.log('❌ 重复注册验证失败 - 应该返回409');
    }
  } catch (error) {
    console.log(`❌ 重复注册验证异常: ${error.message}`);
  }
}

/**
 * 测试用户登录接口
 */
async function testUserLogin() {
  console.log('\\n🔐 测试用户登录接口...');
  
  try {
    // 测试成功登录
    const response = await makeRequest('POST', '/api/sso/login', {
      username: TEST_USER.username,
      password: TEST_USER.password
    });
    
    if (response.statusCode === 200 && response.body.success) {
      console.log('✅ 用户登录成功');
      console.log(`   Session ID: ${response.body.data.sessionInfo.sessionId}`);
      return true;
    } else {
      console.log(`❌ 用户登录失败: ${response.statusCode} - ${response.body.message}`);
      return false;
    }
  } catch (error) {
    console.log(`❌ 用户登录异常: ${error.message}`);
    return false;
  }
}

/**
 * 测试登录状态验证接口
 */
async function testValidateSession() {
  console.log('\\n✅ 测试登录状态验证接口...');
  
  try {
    const response = await makeRequest('GET', '/api/sso/validate');
    
    if (response.statusCode === 200 && response.body.success) {
      console.log('✅ 登录状态验证成功');
      console.log(`   当前用户: ${response.body.data.user.username}`);
      return true;
    } else {
      console.log(`❌ 登录状态验证失败: ${response.statusCode} - ${response.body.message}`);
      return false;
    }
  } catch (error) {
    console.log(`❌ 登录状态验证异常: ${error.message}`);
    return false;
  }
}

/**
 * 测试获取用户信息接口
 */
async function testGetUserInfo() {
  console.log('\\n👤 测试获取用户信息接口...');
  
  try {
    const response = await makeRequest('GET', '/api/sso/userinfo');
    
    if (response.statusCode === 200 && response.body.success) {
      console.log('✅ 获取用户信息成功');
      console.log(`   用户名: ${response.body.data.username}`);
      console.log(`   邮箱: ${response.body.data.email}`);
      return true;
    } else {
      console.log(`❌ 获取用户信息失败: ${response.statusCode} - ${response.body.message}`);
      return false;
    }
  } catch (error) {
    console.log(`❌ 获取用户信息异常: ${error.message}`);
    return false;
  }
}

/**
 * 测试用户登出接口
 */
async function testUserLogout() {
  console.log('\\n🚪 测试用户登出接口...');
  
  try {
    const response = await makeRequest('POST', '/api/sso/logout');
    
    if (response.statusCode === 200 && response.body.success) {
      console.log('✅ 用户登出成功');
      return true;
    } else {
      console.log(`❌ 用户登出失败: ${response.statusCode} - ${response.body.message}`);
      return false;
    }
  } catch (error) {
    console.log(`❌ 用户登出异常: ${error.message}`);
    return false;
  }
}

/**
 * 测试登出后的状态验证
 */
async function testValidateAfterLogout() {
  console.log('\\n🔒 测试登出后的状态验证...');
  
  try {
    const response = await makeRequest('GET', '/api/sso/validate');
    
    if (response.statusCode === 401) {
      console.log('✅ 登出后状态验证正常 - 需要重新登录');
      return true;
    } else {
      console.log(`❌ 登出后状态验证失败: ${response.statusCode} - 应该返回401`);
      return false;
    }
  } catch (error) {
    console.log(`❌ 登出后状态验证异常: ${error.message}`);
    return false;
  }
}

/**
 * 运行所有测试
 */
async function runAllTests() {
  console.log('🚀 开始运行SSO API测试...\\n');
  
  const results = [];
  
  // 1. 健康检查
  results.push(await testHealthCheck());
  
  // 如果健康检查失败，说明服务器未启动
  if (!results[0]) {
    console.log('\\n❌ 服务器未启动，请先运行: npm run dev');
    return;
  }
  
  // 2. 用户注册测试
  results.push(await testUserRegistration());
  
  // 3. 参数验证测试
  await testValidation();
  
  // 4. 用户登录测试
  results.push(await testUserLogin());
  
  // 5. 登录状态验证测试
  results.push(await testValidateSession());
  
  // 6. 获取用户信息测试
  results.push(await testGetUserInfo());
  
  // 7. 用户登出测试
  results.push(await testUserLogout());
  
  // 8. 登出后状态验证测试
  results.push(await testValidateAfterLogout());
  
  // 统计结果
  const passedTests = results.filter(result => result === true).length;
  const totalTests = results.length;
  
  console.log('\\n📊 测试结果统计:');
  console.log(`✅ 通过: ${passedTests}/${totalTests}`);
  console.log(`❌ 失败: ${totalTests - passedTests}/${totalTests}`);
  
  if (passedTests === totalTests) {
    console.log('\\n🎉 所有测试通过！SSO系统运行正常。');
  } else {
    console.log('\\n⚠️  部分测试失败，请检查服务器配置和数据库连接。');
  }
}

// 运行测试
if (require.main === module) {
  runAllTests().catch(console.error);
}

module.exports = { runAllTests };
